#include "serial.h"

//系统自带的配置结构体
/*----------指令名--------------*/
unsigned char cmd_STOP[5] = {0xFF, 0x00, 0x00, 0x00, 0xFF};              //停止
unsigned char cmd_ADVANCE[5] = {0xFF, 0x00, 0x01, 0x00, 0xFF};           //前进
unsigned char cmd_RETREAT[5] = {0xFF, 0x00, 0x02, 0x00, 0xFF};           //后退
unsigned char cmd_TURN_LEFT[5] = {0xFF, 0x00, 0x03, 0x00, 0xFF};         //左转
unsigned char cmd_TURN_RIGHT[5] = {0xFF, 0x00, 0x04, 0x00, 0xFF};        //右转
unsigned char cmd_TURN_LEFT_FRONT[5] = {0xFF, 0x00, 0x05, 0x00, 0xFF};   //左前传
unsigned char cmd_TURN_LEFT_BEHIND[5] = {0xFF, 0x00, 0x06, 0x00, 0xFF};  //左后转
unsigned char cmd_TURN_RIGHT_FRONT[5] = {0xFF, 0x00, 0x07, 0x00, 0xFF};  //右前转
unsigned char cmd_TURN_RIGHT_BEHIND[5] = {0xFF, 0x00, 0x08, 0x00, 0xFF}; //右后转

int uart_init()
{
    struct termios Opt;
    int tty_fd = -1;
    int rv = -1;
    tty_fd = open("/dev/ttySAC0", O_RDWR | O_NOCTTY | O_NDELAY); //打开串口设备ttyUSB0
    if (tty_fd < 0)
    {
        perror("open");
        close(tty_fd);
    }
    else
    {
        printf("Open Success!\n");
    }

    fcntl(tty_fd, F_SETFL, 0);
    printf("ttf_fd=%d\n", tty_fd);

    memset(&Opt, 0, sizeof(Opt));

    rv = tcgetattr(tty_fd, &Opt); //获取原有的串口属性的配置
    if (rv != 0)
    {
        printf("tcgetattr() failed:%s\n", strerror(errno));
        close(tty_fd);
    }

    Opt.c_cflag |= (CLOCAL | CREAD); // CREAD 开启串行数据接收，CLOCAL并打开本地连接模式
    Opt.c_oflag &= ~(ONLCR | OCRNL);
    Opt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    Opt.c_iflag &= ~(ICRNL | INLCR);
    Opt.c_iflag &= ~(IXON | IXOFF | IXANY);

    cfsetispeed(&Opt, B9600);
    cfsetospeed(&Opt, B9600);

    Opt.c_cflag &= ~CRTSCTS; /*无硬件流控*/

    Opt.c_cflag &= ~CSIZE; // 先使用CSIZE做位屏蔽

    Opt.c_cflag |= CS8; //设置8位数据位

    Opt.c_cflag &= ~PARENB; //无校验位
    Opt.c_iflag &= ~INPCK;

    /* 设置115200波特率  */

    Opt.c_cflag &= ~CSTOPB; /* 设置一位停止位; */

    Opt.c_oflag &= ~OPOST;
    Opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

    Opt.c_cc[VTIME] = 0; /* 非规范模式读取时的超时时间;*/

    Opt.c_cc[VMIN] = 0; /* 非规范模式读取时的最小字符数*/

    tcflush(tty_fd, TCIFLUSH); /* tcflush清空终端未完成的输入/输出请求及数据；TCIFLUSH表示清空正收到的数据，且不读取出来 */

    if ((tcsetattr(tty_fd, TCSANOW, &Opt)) != 0) //让以上设置全部生效.
    {
        printf("tcsetattr failed:%s\n", strerror(errno));
        close(tty_fd);
    }
    return tty_fd;
}

// /********测试使用*************/
// int main()
// {

//     int wr_num;
//     int tty_fd = uart_init();
//     wr_num = write(tty_fd, cmd_ADVANCE, sizeof(cmd_ADVANCE));
//     sleep(10);
//     wr_num = write(tty_fd, cmd_STOP, sizeof(cmd_STOP));
//     return 0;
// }
